package com.ruoyi.project.wx.controller;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.bootdo.MD5Utils;
import com.ruoyi.common.utils.bootdo.R;
import com.ruoyi.common.utils.bootdo.UuidUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.wx.domain.MemberUserDO;
import com.ruoyi.project.wx.service.MemberUserService;
import com.ruoyi.project.wx.service.OrderComService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户,会员Controller
 *
 * @author long
 * @date 2021-04-15
 */
@RestController
@RequestMapping("/wx/wxMemberUser")
public class MemberUserController extends BaseController
{
	@Autowired
	private MemberUserService memberUserService;

	@Autowired
	private OrderComService orderComService;

	/**
	 * 查询用户,会员列表
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxMemberUser:list')")
	@GetMapping("/list")
	public TableDataInfo list(MemberUserDO memberUser)
	{
		startPage();
		Map<String, Object> stringObjectMap = BeanUtil.beanToMap(memberUser);
		stringObjectMap.put("delFlag","0");
		stringObjectMap.put("sort","create_at");
		stringObjectMap.put("order","desc");
		List<MemberUserDO> memberUserList = memberUserService.likeList(stringObjectMap);
		for (MemberUserDO memberUserDO : memberUserList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", memberUserDO.getId());
			Map<String,Object> moneyMap = orderComService.getMemberCom(map);
			memberUserDO.setMoney(new BigDecimal(moneyMap.get("kPrice").toString()));
			/*memberUserDO.setFreeze(new BigDecimal(moneyMap.get("dPrice").toString()));*/
			//params.put("userId",memberUserDO.getId());
			BigDecimal shoppingNum = memberUserService.getShoppingNum(map);
			memberUserDO.setFreeze(shoppingNum);
		}
		return getDataTable(memberUserList);
	}

	/**
	 * 导出用户,会员列表
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxMemberUser:export')")
	@Log(title = "用户,会员", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(MemberUserDO memberUser)
	{
		Map<String, Object> stringObjectMap = BeanUtil.beanToMap(memberUser);
		List<MemberUserDO> memberUserList = memberUserService.list(stringObjectMap);
		for (MemberUserDO memberUserDO : memberUserList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", memberUserDO.getId());
			Map<String,Object> moneyMap = orderComService.getMemberCom(map);
			memberUserDO.setMoney(new BigDecimal(moneyMap.get("kPrice").toString()));
			/*memberUserDO.setFreeze(new BigDecimal(moneyMap.get("dPrice").toString()));*/
			//params.put("userId",memberUserDO.getId());
			BigDecimal shoppingNum = memberUserService.getShoppingNum(map);
			memberUserDO.setFreeze(shoppingNum);
		}
		ExcelUtil<MemberUserDO> util = new ExcelUtil<MemberUserDO>(MemberUserDO.class);
		return util.exportExcel(memberUserList, "wxMemberUser");
	}

	/**
	 * 获取用户,会员详细信息
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxMemberUser:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") String id)
	{
		return AjaxResult.success(memberUserService.get(id));
	}

	/**
	 * 新增用户,会员
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxMemberUser:add')")
	@Log(title = "用户,会员", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody MemberUserDO memberUser)
	{
		memberUser.setDisabled(0);
		memberUser.setDelFlag(0);
		memberUser.setFreeze(new BigDecimal("0.00"));
		memberUser.setId(UuidUtil.get32UUID());
		memberUser.setMoney(new BigDecimal("0.00"));
		memberUser.setUpdateAt(new Date());
		memberUser.setCreateAt(new Date());
		if(memberUser.getIntroUser()==null||"".equals(memberUser.getIntroUser())){
			memberUser.setIntroUser("0");
		}
		return toAjax(memberUserService.save(memberUser));
	}

	/**
	 * 修改用户,会员
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxMemberUser:edit')")
	@Log(title = "用户,会员", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody MemberUserDO memberUser)
	{
		if(memberUser.getPassword()!=null&&memberUser.getPassword().length()<=10){
			memberUser.setPassword(MD5Utils.encrypt(memberUser.getPhone(),memberUser.getPassword()));
		}
//		MemberUserDO memberUserDO = memberUserService.get(memberUser.getId());
//		MemberUserDO memberUserDO1 = memberUserService.get(memberUser.getIntroUser());
//		if(memberUserDO.getLevel()<=memberUserDO1.getLevel()){
//			return toAjax(0);
//
//		}
//		memberUserDO.setIntroUser(memberUser.getIntroUser());
		memberUser.setUpdateAt(new Date());

		return toAjax(memberUserService.update(memberUser));
	}

	/**
	 * 删除用户,会员
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxMemberUser:remove')")
	@Log(title = "用户,会员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable String[] ids)
	{
		if(ids.length>0){
			for (String string : ids) {
				MemberUserDO memberUser = memberUserService.get(string);
				memberUser.setDelFlag(1);
				memberUser.setUpdateAt(new Date());
				memberUserService.update(memberUser);
			}
		}
		return toAjax(ids.length);
		//return toAjax(memberUserService.deleteMemberUserByIds(ids));
	}

	/*
    /*
        * 个人业绩图表
        * *//*
	@RequestMapping( "/monthMoneyEcharts")
	@ResponseBody
	public R monthMoneyEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.getOrderEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		BigDecimal[] money = new BigDecimal[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("y").toString());
			money[i] = new BigDecimal(map.get("money").toString());
		}
		return R.ok().put("month",month).put("number",number).put("money", money);
	}

	/*
	 * 平台业绩图表
	 * */

	@RequestMapping( "/allMoneyEcharts")
	@ResponseBody
	public R allMoneyEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allMoneyEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		BigDecimal [] money = new BigDecimal[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("number").toString());
			money[i] = new BigDecimal(map.get("money").toString());
		}
		return R.ok().put("month", month).put("number",number).put("money", money);
	}

	/*
	 * 平台会员人数图表
	 * */
	@RequestMapping( "/allUserEcharts")
	@ResponseBody
	public R allUserEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allUserEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("number").toString());
		}
		return R.ok().put("month",month).put("number", number);
	}

	/*
	 * 后台查询余额
	 * */
	@GetMapping("/goMoneyList/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String goMoneyList(@PathVariable("id") String id, Model model){
		model.addAttribute("userId", id);
		return "wx/memberUser/money";
	}

	/*@ResponseBody
	@GetMapping("/getMoneyList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getMoneyList(@RequestParam Map<String, Object> params){
		//查询余额列表
		Query query = new Query(params);
		List<Map<String,Object>> list = memberUserService.getMoneyListByUser(query);
		int total = memberUserService.getMoneyListByUserCount(query);
		PageUtils pageUtils = new PageUtils(list, total);
		return pageUtils;
	}

	*//**
	 * 导出余额记录excel表格
	 *//*
	@RequestMapping( "/getmoneyExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void getmoneyExcel(@RequestParam() Map<String,Object> params,
							  HttpServletResponse response, HttpServletRequest request){
		try
		{
			String userId = params.get("userId").toString();
			String name = memberUserService.get(userId).getName();
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getMoneyListByUser(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+"余额变动记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.exportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	*//*
	 * 得到直推人信息
	 * *//*
	@GetMapping("/getFather/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String getFather(@PathVariable("id") String id,Model model){
		MemberUserDO memberUser = memberUserService.get(id);
		MemberUserDO fatherUser = memberUserService.get(memberUser.getIntroUser());
		if (fatherUser == null) {
			fatherUser = new MemberUserDO();
		}
		model.addAttribute("fatherUser", fatherUser);
		model.addAttribute("userId", id);
		return "wx/memberUser/getFather";
	}
	*//*
	 * 修改用户等级
	 * *//*
	@GetMapping("/editLevel/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String editLevel(@PathVariable("id") String id,Model model){
		MemberUserDO memberUser = memberUserService.get(id);
		model.addAttribute("memberUser", memberUser);
		return "wx/memberUser/editLevel";
	}
	*//*
	 * 修改用户等级
	 * *//*
	@ResponseBody
	@RequestMapping("/updateLevel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public R updateLevel(MemberUserDO memberUser){
		memberUser.setCreateAt(new Date());
		memberUser.setIntroUser("0");
		memberUserService.update(memberUser);
		return R.ok();
	}*/
	/*
	 * 得到直推人信息
	 *
	@ResponseBody
	@RequestMapping("/updateFather")
	@RequiresPermissions("wx:memberUser:memberUser")
	public R updateFather( MemberUserDO memberUser){
		memberUserService.update(memberUser);
		return R.ok();
	}

	//跳转我的团队页面
	@GetMapping("/getTeam/{id}")
	String getGoods(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);

		model.addAttribute("userId", userId);
		return "wx/memberUser/team";
	}
	@ResponseBody
	@GetMapping("/getTeamInfo")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getTeamInfo(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getMyFansH(query);
		int total = memberUserService.getMyFansHCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	 */

	/* //跳转个人消费记录页面
	@GetMapping("/getShopping/{id}")
	String getShopping(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);

		model.addAttribute("userId", userId);
		return "wx/memberUser/shopping";
	}
	@ResponseBody
	@GetMapping("/getShoppingList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getShoppingList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getShoppingList(query);
		int total = memberUserService.getShoppingListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	/**
	 * 导出个人消费记录excel表格
	 */
	@RequestMapping( "/getShoppingExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void getShoppingExcel(@RequestParam() Map<String,Object> params,
								 HttpServletResponse response,HttpServletRequest request){
		try
		{
			String userId = params.get("userId").toString();
			String name = memberUserService.get(userId).getName();
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getShoppingList(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+"消费记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.shoppingExportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	//跳转平台收入记录页面
	@GetMapping("/getPTShopping")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	String getPTShopping( Model model) {
//		UserDO userDO = userService.get(userId);
		return "wx/memberUser/ptShopping";
	}
	/*@ResponseBody
	@GetMapping("/getPTShoppingList")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	public PageUtils getPTShoppingList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getShoppingList(query);
		int total = memberUserService.getShoppingListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	/*
	 * 平台收入总额
	 * */
	@RequestMapping( "/getShoppingNum")
	@ResponseBody
	public R getShoppingNum(@RequestParam Map<String,Object> params){
		BigDecimal shoppingNum = memberUserService.getShoppingNum(params);
		return R.ok().put("data",shoppingNum);
	}

	/**
	 * 导出平台收入记录excel表格
	 */
	/*@RequestMapping( "/getPTShoppingExcel")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	public void getPTShoppingExcel(@RequestParam() Map<String,Object> params,
								   HttpServletResponse response,HttpServletRequest request){
		try
		{
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getShoppingList(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("平台收入记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.shoppingExportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}


	@GetMapping("/tree/{id}")
	@ResponseBody
	public Tree<MemberUserDO> tree(@PathVariable("id") String userId) {
		Tree<MemberUserDO> tree = new Tree<MemberUserDO>();
		tree = memberUserService.getTree(userId);
		return tree;
	}

	@GetMapping("/treeView/{id}")
	String treeView(Model model,@PathVariable("id") String userId) {

		model.addAttribute("userId",userId);
		return  prefix+"/deptTree";
	}
*/
}
